import time, json
import requests
from PIL import Image
import streamlit as st
import FlocApi
from requests.packages.urllib3.exceptions import InsecureRequestWarning

SN = ''

def refresh(SN):
    print('初次')
    print(session_state['lastImgTime'])
    if 'showLength' not in session_state:
        session_state['showLength'] = '5'
    show_length = int(session_state['showLength'])
    
    # 查询“0”时间，
    imgGroup, names, first, last = FlocApi.getRecentImageLink(SN,show_length, 0, 'png')    
    if imgGroup == []:
        print('错误查询')
    print(imgStartTime,'自11',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(last )),
                        '至',time.strftime('%H:%M:%S',time.localtime(first )))
    a = []
    a.append(int(first))
    a.append(int(last))
    # print('last',time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(last )),
    #                     'first',time.strftime('%H:%M:%S',time.localtime(first )))
    
    session_state['lastImgTime'] = json.dumps(a)        
    session_state['last'] = json.dumps(last)
    session_state['first'] = json.dumps(first)
    # print('hello ',session_state)

imgGroup = []

def page_home():
    global imgGroup
    global names
    global mode, imgStartTime, lastImgTime 

    if 'lastImgTime' not in session_state:
        session_state['lastImgTime'] = '[]'
    if 'firstImgTime' not in session_state:
        session_state['firstImgTime'] = int(time.time())
    
    
    with st.container(border=False):        
        SN = session_state['SN']        
        # print('\nSN',SN)
        if SN != '':
            imgGroup, names, first, last = FlocApi.getRecentImageLink(SN,show_length,0,'png')
            # print('ab',session_state['lastImgTime'])
            if session_state['lastImgTime'] == '' or session_state['lastImgTime'] == '[]':             
                refresh(session_state['SN'])
            button_col = st.columns([2,4,1,1]) 
            with button_col[-1]:
                if len(session_state['lastImgTime'])>1:
                    if st.button('》'):
                        a = json.loads(session_state['lastImgTime'])
                        if len(a) > 1:
                            a.pop()
                        imgStartTime = int(a[-1])
                        imgGroup, names, first, last = FlocApi.getRecentImageLink(SN,show_length, imgStartTime,'png')
                        # a.append(last)
                        session_state['lastImgTime'] = json.dumps(a)    
                        print('\n更新',session_state['lastImgTime']) 

            with button_col[-2]: 
                if st.button('《'):                                      
                    a = json.loads(session_state['lastImgTime'])                    
                    imgStartTime = int(a[-1])
                    print(a)
                    print('前翻时间', time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(imgStartTime )))
                    imgGroup, names, first, last = FlocApi.getRecentImageLink(SN,show_length, imgStartTime,'png')
                    # print('\n更新前',session_state['lastImgTime'])                        
                    a.append(last)
                    session_state['lastImgTime'] = json.dumps(a)
                    print('\n更新',session_state['lastImgTime'])    

            with button_col[0]:
                last = int(session_state['last'])
                first = int(session_state['first'])            
                st.write(time.strftime('%Y-%m-%d',time.localtime(last)))
                st.write(time.strftime('%H:%M',time.localtime(last)),'~',time.strftime('%H:%M',time.localtime(first )))
                # st.write(session_state['lastImgTime'])                                  
            
            if session_state['imgSize'] == '大':
                img_size = 300
            elif session_state['imgSize'] == '中':
                img_size = 200
            else:
                img_size = 100
            
            
            if len(imgGroup) > 0: 
                for i in range(len(imgGroup)):  
                    # print('imglist', imgGroup[i])
                    try:
                        filename = imgGroup[i][0]['path']
                    except Exception as e:
                        print('图片读取错误',e)
                        break
                    key = filename.split('.')[-2]
                    key = key.split('-')[-1]
                    last = int(session_state['last'])
                    first = int(session_state['first'])                    
                    success, flocList = FlocApi.getFlocStatics(SN,key, str(first - last), str(last),str(last)) 
                    if not success:                        
                        print('\n 矾花统计数据无效 \n')
                    with st.container(border=True):                        
                        st.write(names[i])
                        columns = st.columns(5)
                        try:
                            num =0                                                                    
                            imgList = imgGroup[i]
                            print('矾花统计',len(flocList))
                            for j in range(len(imgList)):
                                cap = time.strftime('%H:%M',time.localtime(int(imgList[j]['time'])))
                                with columns[num % 5]:                                                     
                                    st.image(imgList[j]['link'], width= img_size, caption=cap)
                                    try:
                                        # print(j,flocList[j])
                                        st.write('数量  '+str(flocList[j]['num']))
                                        st.write('尺寸 '+str(int(flocList[j]['diameter80']))+'um')
                                    except Exception as e:
                                        print('矾花统计错误',e)
                                    # st.image(image['link'])
                                    # st.write(num,time.strftime('%H:%M',time.localtime(int(image['time'])))) 
                                num += 1                        
                        except Exception as e:
                            print(i, e)
    

def page_about():    
    st.title('关于矾花助手')
    st.write('FlocWise Copyright')
    st.title('开发团队')    
    st.write('Jackey Gu 2023')



requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# 设置初始页面为Home
st.set_page_config(page_title='矾花助手', page_icon=None, layout="wide", initial_sidebar_state="auto", menu_items=None)
session_state = st.session_state
if 'page' not in session_state:
    session_state['page'] = 'Home'
    
if 'SN' not in session_state:
    session_state['SN'] = ''

deviceList = FlocApi.getDeviceList('623576f170368a206e50c8ee')
SN = deviceList[0]
SN = SN.split(' ')[0]
session_state['SN'] = SN

imgStartTime = time.time()


st.sidebar.header('矾花助手')        
st.sidebar.write('V0.1.1')   
st.sidebar.divider()

device = st.sidebar.selectbox('选择设备', deviceList)            
print(session_state['SN'],device)
session_state['SN'] = device.split(' ')[0]
if session_state['SN'] != device.split(' ')[0]:
    session_state['SN'] = device.split(' ')[0]
    print('切换到', session_state['SN'])
    if 'lastImgTime' not in session_state:
        session_state['lastImgTime'] = '[]'
    refresh(session_state['SN'])

show_length = st.sidebar.selectbox('每页显示', [5,10,20])            
session_state['showLength'] = show_length
session_state['imgSize'] = st.sidebar.selectbox('图片大小', ['小','中','大'])            

page_home()


button_style = """
    <style>
        .stButton>button {
            background-color: #FF5733;
            color: white;
            font-size: 16px;
        }
    </style>
"""

